import axios from 'axios'
import type { AxiosInstance } from 'axios'


const request:AxiosInstance = axios.create({
    baseURL:'/',//本地
    timeout: 60000,
})

// 添加请求拦截器
request.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么  设置token
    config.headers.token = localStorage.getItem('token') || '';
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
request.interceptors.response.use(function (response) {
    
    if (response.data.data) {
        console.log(6,response.data);
        return response.data
    } else {
        return response;
    }
//   return response.data
}, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error);
});
interface iConfig {
    url: string,
    data?: any,
    headers?: any,
    method?: string,
}
export default function ajax(config:iConfig) {

    const { url = '', data = {}, headers = {}, method = 'get' } = config

    switch (method.toUpperCase()) {
        case 'GET':
            return request.get(url, { params: data });
        case 'POST':

            if (headers['content-type'] == 'application/x-www-form-urlencoded') {
                const obj = new URLSearchParams()
                for (const key in data) {
                    obj.append(key, data[key])
                }
                return request.post(url, obj, { headers })
            }
            if (headers['content-type'] == 'multipart/form-data') {
                const obj = new FormData()
                for (const key in data) {
                    obj.append(key, data[key])
                }
                return request.post(url, obj, { headers })
            }
            return request.post(url, data)
        case 'DELETE':
            return request.delete(url, { data })
        case 'PUT':
            return request.put(url, data)
        case 'PATCH':
            return request.patch(url, data)
        default:
            return request.request(config)
    }
}